<?php

namespace lib\Oss;

class ImgCompress
{
    private $src;
    private $image;
    private $imageinfo;
    private $percent = 1;

    /**
     * 图片压缩
     * @param string $src 源图
     * @param float $percent 压缩比例
     */
    public function __construct($src, $percent = 1)
    {
        $this->src = $src;
        $this->percent = $percent;
    }
    /** 高清压缩图片
     * @param string $saveName 提供图片名（可不带扩展名，用源图扩展名）用于保存。或不提供文件名直接显示
     */
    public function compressImg($saveName = '')
    {
        $this->_openImage();
        if (!empty($saveName)) $this->_saveImage($saveName);  //保存
        else $this->_showImage();
    }

    /**
     * 内部：打开图片
     */
    private function _openImage()
    {
        list($width, $height, $type, $attr) = getimagesize($this->src);
        $this->imageinfo = array(
            'width' => $width,
            'height' => $height,
            'type' => image_type_to_extension($type, false),
            'attr' => $attr
        );
        $fun = "imagecreatefrom" . $this->imageinfo['type'];
        $this->image = $fun($this->src);
        $this->_thumpImage();
    }

    /**
     * 内部：操作图片
     */
    private function _thumpImage()
    {
        $new_width = $this->imageinfo['width'] * $this->percent;
        $new_height = $this->imageinfo['height'] * $this->percent;
        $image_thump = imagecreatetruecolor($new_width, $new_height);
        //将原图复制带图片载体上面，并且按照一定比例压缩,极大的保持了清晰度
        imagecopyresampled($image_thump, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->imageinfo['width'], $this->imageinfo['height']);
        imagedestroy($this->image);
        $this->image = $image_thump;
    }

    /**
     * 输出图片:保存图片则用saveImage()
     */
    private function _showImage()
    {
        header('Content-Type: image/' . $this->imageinfo['type']);
        $funcs = "image" . $this->imageinfo['type'];
        $funcs($this->image);
        imagedestroy($this->image);
    }

    /**
     * 保存图片到硬盘：
     * @param  string $dstImgName
     */
    private function _saveImage($dstImgName)
    {
        $this->_mkPath($dstImgName);
        $funcs = "image" . $this->imageinfo['type'];
        $funcs($this->image, $dstImgName);
        imagedestroy($this->image);
    }

    /**
     * 创建图片文件
     * @param $path
     */
    private function _mkPath($path){
        $arr = explode('/',$path);
        array_pop($arr);
        $dir = implode('/',$arr);
        if (!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        if (!file_exists($path)){
            touch($path);
        }
    }

}